package cn.kgc.springcloud.controller;

import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/7
 * @Description:
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @GetMapping
    public List<ClazzVO> list() {

        return clazzService.getClazzVo();
    }


    @DeleteMapping("{id}")
    public Boolean deleteById(@PathVariable("id") Integer id) {
        return clazzService.removeById(id);
    }

    @PostMapping
    public Clazz addClazz(MultipartFile file, String name, Integer tagId) {

        // 文件上传
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        // xxxx-xxxx-xxx
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String lastName = uuid + "." + filenameExtension;

        // 文件上传
        File file1 = new File("D:\\upload\\" + lastName);
        try {
            file.transferTo(file1);

        } catch (IOException e) {
            e.printStackTrace();
        }

        Clazz clazz = new Clazz();
        clazz.setName(name);
        clazz.setTagid(tagId);
        clazz.setPath(lastName);
        clazzService.save(clazz);
        return clazz;
    }

    @GetMapping("{id}")
    public Clazz getById(@PathVariable("id") Integer id) {
      return   clazzService.getById(id);
    }
}
